<template>
  <div class="book-list-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="图书名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入图书名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="queryParams.author" placeholder="请输入作者" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select class="category-select" v-model="queryParams.categoryId" placeholder="请选择分类" clearable>
            <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>图书列表</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>添加图书
          </el-button>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="bookList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="图书名称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="author" label="作者" min-width="120" show-overflow-tooltip />
        <el-table-column prop="publisher" label="出版社" min-width="150" show-overflow-tooltip />
        <el-table-column prop="isbn" label="ISBN" min-width="120" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="分类" min-width="100" />
        <el-table-column prop="price" label="价格" min-width="100">
          <template #default="scope">
            {{ scope.row.price ? `¥${scope.row.price}` : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" align="center" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="primary" link @click="handleStockUpdate(scope.row)">
              <el-icon><Goods /></el-icon>库存
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        v-if="total > 0"
        v-model:current-page="queryParams.current"
        v-model:page-size="queryParams.size"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 库存更新对话框 -->
    <el-dialog v-model="stockDialogVisible" title="更新库存" width="400px" append-to-body>
      <el-form :model="stockForm" label-width="80px">
        <el-form-item label="图书名称">
          <span>{{ stockForm.name }}</span>
        </el-form-item>
        <el-form-item label="当前库存">
          <span>{{ stockForm.currentStock }}</span>
        </el-form-item>
        <el-form-item label="变更数量">
          <el-input-number v-model="stockForm.changeStock" :min="-stockForm.currentStock" :max="999" />
          <div class="stock-tip">正数增加库存，负数减少库存</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="stockDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitStockUpdate" :loading="stockUpdateLoading">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getBookList, deleteBook, updateBookStock } from '../../api/book'
import { getAllCategories } from '../../api/category'

const router = useRouter()

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 10,
  name: '',
  author: '',
  categoryId: undefined
})

// 图书列表数据
const bookList = ref([])
const total = ref(0)
const loading = ref(false)

// 分类选项
const categoryOptions = ref([])

// 获取图书列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getBookList(queryParams)
    if (res.data) {
      bookList.value = res.data.records || []
      total.value = res.data.total || 0
      
      // 处理分类名称
      bookList.value.forEach(book => {
        const category = categoryOptions.value.find(c => c.id === book.categoryId)
        book.categoryName = category ? category.name : '未分类'
      })
    }
  } catch (error) {
    console.error('获取图书列表失败:', error)
    ElMessage.error('获取图书列表失败')
  } finally {
    loading.value = false
  }
}

// 获取所有分类
const fetchCategories = async () => {
  try {
    const res = await getAllCategories()
    if (res.data) {
      categoryOptions.value = res.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 搜索按钮点击事件
const handleQuery = () => {
  queryParams.current = 1
  getList()
}

// 重置按钮点击事件
const resetQuery = () => {
  queryParams.name = ''
  queryParams.author = ''
  queryParams.categoryId = undefined
  handleQuery()
}

// 分页大小改变事件
const handleSizeChange = (size) => {
  queryParams.size = size
  getList()
}

// 页码改变事件
const handleCurrentChange = (current) => {
  queryParams.current = current
  getList()
}

// 添加图书按钮点击事件
const handleAdd = () => {
  router.push('/book/add')
}

// 编辑图书按钮点击事件
const handleEdit = (row) => {
  router.push(`/book/edit/${row.id}`)
}

// 删除图书按钮点击事件
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除图书「${row.name}」吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteBook(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除图书失败:', error)
      ElMessage.error('删除图书失败')
    }
  }).catch(() => {})
}

// 库存更新相关
const stockDialogVisible = ref(false)
const stockUpdateLoading = ref(false)
const stockForm = reactive({
  id: undefined,
  name: '',
  currentStock: 0,
  changeStock: 0
})

// 打开库存更新对话框
const handleStockUpdate = (row) => {
  stockForm.id = row.id
  stockForm.name = row.name
  stockForm.currentStock = row.stock
  stockForm.changeStock = 0
  stockDialogVisible.value = true
}

// 提交库存更新
const submitStockUpdate = async () => {
  if (stockForm.changeStock === 0) {
    ElMessage.warning('变更数量不能为0')
    return
  }
  
  // 计算最终库存 = 当前库存 + 变更数量
  const finalStock = stockForm.currentStock + stockForm.changeStock
  
  // 检查最终库存是否合法
  if (finalStock < 0) {
    ElMessage.warning('库存不能小于0')
    return
  }
  
  stockUpdateLoading.value = true
  const stock = finalStock
  try {
    const res = await updateBookStock(stockForm.id, stock)
    if (res.code === 200) {
      ElMessage.success('库存更新成功')
      stockDialogVisible.value = false
      getList()
    } else {
      ElMessage.error(res.message || '库存更新失败')
    }
  } catch (error) {
    console.error('更新库存失败:', error)
    ElMessage.error('更新库存失败: ' + error.message)
  } finally {
    stockUpdateLoading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchCategories()
  getList()
})
</script>

<style scoped>
.book-list-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stock-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.category-select {
  width: 100px;
}
</style>